package com.xixibaby.redis.service;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONObject;
import com.xixibaby.core.*;
import com.xixibaby.core.service.DBServiceImpl;
import com.zengtengpeng.operation.RedissonCollection;
import com.zengtengpeng.operation.RedissonObject;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RList;
import org.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class RedisServiceImpl<
        MAPPER extends SuperMapper<PO>,
        PO extends SuperPO,
        RESPONSE extends SuperResponse,
        REQUEST extends SuperRequest,
        CONCATER extends SuperConverter<PO,RESPONSE,REQUEST>>
        extends DBServiceImpl<MAPPER,PO,RESPONSE,REQUEST,CONCATER> {

    @Autowired
    private RedissonObject redissonObject;

    private String getCacheKey(PO po){
        String simpleName = po.getClass().getSimpleName().toUpperCase();
        return simpleName + ":" + getId(po);
    }

    @Override
    protected void deleteCache(PO vo) {
        log.info("删除：【{}】【{}】", vo.getClass().getSimpleName(),getId(vo));
        redissonObject.delete(getCacheKey(vo));
    }

    private Object getId(PO po){
        return ReflectUtil.getFieldValue(po, "id");
    }

    @Override
    protected void insertCache(PO vo) {
        log.info("添加到缓存：【{}】【{}】", vo.getClass().getSimpleName(),getId(vo));
        String s = JSONObject.toJSONString(vo);
        redissonObject.setValue(getCacheKey(vo), s,1000 * 60 * 60L);
    }

    @Override
    protected void updateCache(PO vo) {
        log.info("更新缓存：【{}】【{}】", vo.getClass().getSimpleName(),getId(vo));
        this.deleteCache(vo);
        Object id = getId(vo);
        this.insertCache(this.mapper.selectById(Long.valueOf(id.toString())));
    }

    @Override
    protected PO selectCacheById(REQUEST vo) {
        PO po = this.concater.toPO(vo);
        Class<? extends SuperPO> clazz = po.getClass();
        String value = redissonObject.getValue(getCacheKey(po));
        log.info("读取缓存：【{}】【{}】【{}】", clazz.getSimpleName(),vo.getId(), Assert.notEmpty(value));
        PO superPO = (PO) JSONObject.parseObject(value,clazz);
        return superPO;
    }
}
